#ifndef DBWORKER_H
#define DBWORKER_H

#include <QObject>
#include <QtSql>
#include <QString>

#include "logger.h"
#include "my_defs.h"
#include "styleloader.h"
#include "mymodel.h"
#include "treemodel.h"

class DBWorker : public QObject
{
    Q_OBJECT
public:
    DBWorker(QObject *parent);

    bool openDb(const QString dbName);
    void closeCurrentDb();

    QSqlDatabase *workDB()  { return mWorkDB; }

    MyTabModel  *tabModel() { return mTabModel; }
    TreeModel   *treeModel(){ return mTreeModel; }

    QString dbName() const  { return mDbName; }
    bool createDB(QString dbName, QString createText);
    bool saveDbAs(const QString newDbName);

    void setCurRec(const int cur) { mCurRec = cur; qDebug()<< QString("CurIndex=%1").arg(mCurRec); }
    int  curRec() { return mCurRec; }

    int findNextFreeId();

    void refreshAllModels();

    bool insertRecord(const int uniqId, const QString name,
                      const int styleId, const QString com,
                      bool doRefresh = true);
    bool batchInsertRecords(QVariantList uniqIds,
                            QVariantList names,
                            QVariantList styleIds,
                            QVariantList comments);

    bool getRecordByUniqId(const int uniqId,
                           QString &name,
                           int &styleId,
                           QString &comment);

    void search(const QString stext);
    QString searchText;
    int searchRowsCount() const;

    bool isDbLoaded() const;

signals:
    void needRefresh();

    void recordDeleted();
    void recordInserted();

private:
    // My reimplemented models
    MyTabModel  *mTabModel;
    TreeModel   *mTreeModel;

    void freeModels();
    void createModels();

    // DBs
    QString mDbName;
    QSqlDatabase *mWorkDB;
    bool mIsDbLoaded;

    int mCurRec;    // current record, which will be in work soon
    int mSearchRowsCount;

public slots:
    void deleteCurRecord();
    bool editCurRecord(const int uniqId, const QString name, const int styleId, const QString com);
};

#endif // DBWORKER_H
